﻿using Angle.Krill.Utils;
using System;
using System.Linq;
using System.Windows.Forms;

namespace Angle.Krill
{
    public partial class IconLibrary : DummyWindow
    {
        private int totalCount = FontAwesomeHelper.Instance.TypeDict.Count;

        private int pageSize = 50;
        private int current = 1;
        public IconLibrary()
        {
            InitializeComponent();
            this.SetStyle(ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer, true);
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
        }

        private void IconLibrary_Load(object sender, EventArgs e)
        {
            this.pager.PageSize = pageSize;
            this.pager.Total = totalCount;

            this.LoadIcon();
        }

        private void LoadIcon()
        {
            BeginInvoke(BeginInvoke);
        }

        private void pager_ValueChanged(int current, int total, int pageSize, int pageTotal)
        {
            this.current = current;
            this.pageSize = pageSize;

            BeginInvoke(BeginInvoke);
        }

        private void BeginInvoke(Func<Delegate, IAsyncResult> beginInvoke)
        {
            flowPanel.PauseLayout = true;
            flowPanel.Controls.Clear();

            string searchContent = this.txtSearchContent.Text.Trim();
            var totalItem = string.IsNullOrEmpty(searchContent) ?
                FontAwesomeHelper.Instance.TypeDict :
                FontAwesomeHelper.Instance.TypeDict.Where(t => t.Key.Contains(searchContent));

            var items = totalItem.Skip(this.pageSize * (this.current - 1)).Take(this.pageSize);

            this.pager.Total = totalItem.Count();
            this.pager.Current = this.current > this.pager.PageTotal ? 1 : this.current;

            foreach (var item in items)
            {
                UCImage ucImage = new UCImage(FontAwesomeHelper.Instance.GetImage(item.Value), item.Key);

                this.flowPanel.Controls.Add(ucImage);
            }

            flowPanel.PauseLayout = false;
        }

        private void txtSearchContent_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                BeginInvoke(BeginInvoke);
            }
        }
    }
}
